import { Injectable } from '@nestjs/common';
import * as OSS from 'ali-oss';

@Injectable()
export class OssUtilService {
  private client: OSS;

  constructor() {
    // 直接使用有效的 OSS 配置
    console.log('=== OSS 服务初始化 ===');
    console.log('使用硬编码的 OSS 配置');
    
    this.client = new OSS({
      region: 'oss-cn-hangzhou',
      accessKeyId: 'LTAI5tQwFqrSAXc6c3E31LrW',
      accessKeySecret: '1ZzR8xAKkWo4gluY9XkeFSKfDio97Y',
      bucket: 'hasmarket',
      endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
    });
    
    console.log('OSS 客户端已初始化');
  }

  async uploadFile(bucket: string, folder: string, filename: string, buffer: Buffer): Promise<any> {
    try {
      const objectName = `${folder}/${filename}`;
      const result = await this.client.put(objectName, buffer);
      
      return {
        url: result.url,
        name: filename,
        etag: (result as any).etag || '',
      };
    } catch (error) {
      console.error('OSS上传错误详情:', error);
      throw new Error(`OSS上传失败: ${error.message}`);
    }
  }

  async deleteFile(bucket: string, folder: string, filename: string): Promise<void> {
    try {
      const objectName = `${folder}/${filename}`;
      await this.client.delete(objectName);
    } catch (error) {
      throw new Error(`OSS删除失败: ${error.message}`);
    }
  }
} 